import { OrderDocument } from '@app/database/schemas/order.schema';
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';

@Injectable()
export class OrdersService {
  constructor(
    @InjectModel('Order')
    private readonly orderModel: Model<OrderDocument>,
  ) {}
  async findAll(userId: string, query: any) {
    let { status = null, page = 1, pageSize = 5 } = query;
    let where: any = { user: userId, status: { $ne: 0 } };
    if (status) {
      where.status.$eq = status;
    }
    page = parseInt(page);
    pageSize = parseInt(pageSize);
    const items = await this.orderModel
      .find(where)
      .populate({
        path: 'cars',
        populate: { path: 'book' },
      })
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .sort({ _id: -1 });
    const total = await this.orderModel.countDocuments(where);
    return { items, total };
  }

  async findOne(userId: string) {
    let order = (
      await this.orderModel.find({ user: userId, status: 0 }).sort({ _id: 1 })
    )[0];
    if (!order) {
      order = await this.orderModel.create({ user: userId, status: 0 });
    }
    return order;
  }

  updateOne(orderId: string, status: number) {
    return this.orderModel.updateOne({ _id: orderId }, { status });
  }
}
